package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"math/rand"
	"path/filepath"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	gomail "gopkg.in/gomail.v2"
)

func main() {
	router := gin.Default()
	router.GET("/test", func(this *gin.Context) {
		//定义收件人
		mailTo := []string{
			"2724213414@qq.com",
			"2728887292@qq.com",
		}
		//邮件主题
		subject := "注册验证码"
		// 邮件正文
		rand.Seed(time.Now().UnixNano())
		randomNumber := rand.Intn(9000) + 1000
		body := "<html><body><p>你的注册验证码为：" + strconv.Itoa(randomNumber) + "。有效时间一分钟。</p>"

		err := SendMail(mailTo, subject, body)
		if err != nil {
			log.Println(err)
			fmt.Println("send fail")
			return
		}

		fmt.Println("send successfully")
		// // SMTP 认证信息
		/* from := "18717085911@163.com"  // 发件人邮箱地址
		password := "" // 发件人邮箱授权码 比如 "BCQSQKLELONYTOBK"
		smtpServer := "smtp.163.com"   // SMTP 服务器地址
		auth := smtp.PlainAuth("", from, password, smtpServer)
		// 邮件内容
		to := []string{
			"2724213414@qq.com",
			"227247259@qq.com",
			"1379533494@qq.com",
		}
		rand.Seed(time.Now().UnixNano())
		randomNumber := rand.Intn(9000) + 1000
		subject := "验证码"                   // 邮件主题
		body := strconv.Itoa(randomNumber) // 邮件正文
		message := fmt.Sprintf("To: %s\r\nSubject: %s\r\n\r\n%s", to, subject, body)

		// 发送邮件
		err := smtp.SendMail("smtp.163.com:465", auth, from, to, []byte(message))
		if err != nil {
			fmt.Println("Failed to send email:", err)
			return
		}
		fmt.Println("Email sent successfully!") */

	})
	router.Run(":80")
}

func SendMail(mailTo []string, subject string, body string) error {
	//定义邮箱服务器连接信息，如果是网易邮箱 pass填密码，qq邮箱填授权码

	//mailConn := map[string]string{
	//  "user": "xxx@163.com",
	//  "pass": "your password",
	//  "host": "smtp.163.com",
	//  "port": "465",
	//}

	mailConn := map[string]string{
		"user": "18717085911@163.com",
		"pass": "BCQSQKLELONYDQBK",
		"host": "smtp.163.com",
		"port": "25",
	}

	port, _ := strconv.Atoi(mailConn["port"]) //转换端口类型为int

	m := gomail.NewMessage()

	m.SetHeader("From", m.FormatAddress(mailConn["user"], "晚风漪官方")) //这种方式可以添加别名，即“XX官方”
	m.SetHeader("To", mailTo...)                                    //发送给多个用户
	m.SetHeader("Subject", subject)                                 //设置邮件主题
	//m.SetBody("text/html", body)                                    //设置邮件正文
	//加上图片
	imgpath := "./猫.png"
	cid, err := addInlineImage(m, imgpath)
	if err != nil {
		fmt.Println(err)
		return err
	}
	body += fmt.Sprintf("<img src=\"%s\"></body></html>", cid)
	m.SetBody("text/html", body)
	d := gomail.NewDialer(mailConn["host"], port, mailConn["user"], mailConn["pass"])

	err = d.DialAndSend(m)
	return err
}

// 将指定路径的文件添加为内联图像，并返回CID。
func addInlineImage(m *gomail.Message, filePath string) (string, error) {
	fileBytes, err := ioutil.ReadFile(filePath)
	if err != nil {
		return "", err
	}
	cid := filepath.Base(filePath)
	//cid := fmt.Sprintf("%s", fileName)

	m.Embed(filePath, gomail.SetCopyFunc(func(wr io.Writer) error {
		_, err := wr.Write(fileBytes)
		return err
	}))

	return cid, nil
}
